﻿#region License
/*
 *CopyRight (c) By Denuvead All Rights Reserved
 *CreateDate:2012-11-17 01:02
 *Info:Tools Class
 */
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.ComponentModel;
using System.Security.Cryptography;

namespace PriErp.Tools
{
    /// <summary>
    /// 工具类
    /// </summary>
    public class Utils
    {
        /// <summary>
        /// 获取指定类型某一字段首个描述
        /// </summary>
        /// <param name="type">类型</param>
        /// <param name="FieldName">字段名</param>
        /// <returns>描述信息</returns>
        public static string GetDescription(Type type, string FieldName)
        {
            string txt = string.Empty;
            FieldInfo fileInfo = type.GetField(FieldName);
            if (fileInfo != null)
            {
                DescriptionAttribute[] da = fileInfo.GetCustomAttributes(typeof(DescriptionAttribute), false)
                                           as DescriptionAttribute[];
                if (da != null && da.Length > 0)
                    txt = da[0].Description;
            }
            return txt;
        }

        /// <summary>
        /// 对象克隆
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="source">对象源</param>
        /// <returns>返回拷贝的新对象</returns>
        public static T Clone<T>(T source)
        {
            var dcs = new System.Runtime.Serialization.DataContractSerializer(typeof(T));
            using (var ms = new System.IO.MemoryStream())
            {
                dcs.WriteObject(ms, source);
                ms.Seek(0, System.IO.SeekOrigin.Begin);
                return (T)dcs.ReadObject(ms);
            }
        }

        /// <summary>
        /// 生成随机数
        /// This method simulates a roll of the dice. The input parameter is the
        /// number of sides of the dice.
        /// </summary>
        /// <param name="NumSides">整数上限</param>
        /// <returns>返回0~NumSides间的一个随机数</returns>
        public static int RollDice(int NumSides)
        {
            // Create a byte array to hold the random value.
            byte[] randomNumber = new byte[1];
            // Create a new instance of the RNGCryptoServiceProvider.
            RNGCryptoServiceProvider Gen = new RNGCryptoServiceProvider();
            // Fill the array with a random value.
            Gen.GetBytes(randomNumber);
            // Convert the byte to an integer value to make the modulus operation easier.
            int rand = Convert.ToInt32(randomNumber[0]);
            // Return the random number mod the number
            // of sides.  The possible values are zero-
            // based, so we add one.
            return rand % (NumSides + 1);
        }
    }
}
